﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using YoutubeVideo.Resources;
using YoutubeVideo.MyClass;
using MyToolkit.Multimedia;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using System.Xml;
using System.IO;

namespace YoutubeVideo
{
    public partial class MainPage : PhoneApplicationPage
    {
        XmlHelper xmlHelper = new XmlHelper();
        StorageHelper Storage = new StorageHelper();

        IEnumerable<VideoItem> data;
        List<VideoItem> Recent=new List<VideoItem>();
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            data = xmlHelper.LoadList();

            Recent=Storage.LoadFromXml("RecentXml.xml");

            if(Recent==null) Recent = new List<VideoItem>();

            InitializeData();

            InitalizeRecent();
        }
        #region Khởi tạo Data Load từ XML cho LongListSelector
        public void InitalizeRecent()
        {
            tileList.ItemsSource = null;
            tileList.ItemsSource = Recent;
        }
        public void InitializeData()
        {
            LListMovie.ItemsSource = GetVideoItemGroup(data);
        }
        private List<Group<VideoItem>> GetVideoItemGroup(IEnumerable<VideoItem> lsData)
        {
            return GetItemGroups(lsData, v => v.Group);
        }
        private static List<Group<T>> GetItemGroups<T>(IEnumerable<T> itemList, Func<T, string> getKeyFunc)
        {
            IEnumerable<Group<T>> groupList = from item in itemList
                                              group item by getKeyFunc(item) into g
                                              orderby g.Key
                                              select new Group<T>(g.Key, g);
            return groupList.ToList();
        }
        private void AddItemToRecent(VideoItem value)
        {
            if (Recent.Count > 0)
            {
                if (Recent.Where(s => s.YoutubeID == value.YoutubeID).Count() <= 0)
                {
                    if (Recent.Count() >= 8)
                    {
                        Recent = Recent.Skip(Recent.Count() - 7).Take(7).ToList();
                    }
                    Recent.Add(value);
                    //Recent.Add(value.getTitleItem());    
                    InitalizeRecent();
                }
            }
            else
            {
                Recent.Add(value);
                //Recent.Add(value.getTitleItem());
                InitalizeRecent();
            }
        }
        #endregion

        #region Play Video in Youtube
        private async void PlayVideo_Click(object sender, System.Windows.Input.GestureEventArgs e)
        {
            VideoItem item = (sender as Image).DataContext as VideoItem;

            if (item != null)
            {
                if (SystemTray.ProgressIndicator != null)
                    SystemTray.ProgressIndicator.IsVisible = true; 
                try
                {
                    await YouTube.PlayWithPageDeactivationAsync(
                        item.YoutubeID, true, YouTubeQuality.QualityHigh);
                    AddItemToRecent(item);
                    InitalizeRecent();
                    Storage.SaveToXml("RecentXml.xml", Recent);
                }
                catch (Exception ex)
                {
                    if (SystemTray.ProgressIndicator != null)
                        SystemTray.ProgressIndicator.IsVisible = false;
                    MessageBox.Show(ex.Message);
                }
            }
        }
        private async void HubTile_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            TileItem item = (sender as HubTile).DataContext as TileItem;

            if (item != null)
            {
                VideoItem video = data.Where(s => s.Title == item.Notification).First();

                if (video != null)
                {
                    if (SystemTray.ProgressIndicator != null)
                        SystemTray.ProgressIndicator.IsVisible = true;
                    try
                    {
                        await YouTube.PlayWithPageDeactivationAsync(
                            video.YoutubeID, true, YouTubeQuality.QualityHigh);
                    }
                    catch (Exception ex)
                    {
                        if (SystemTray.ProgressIndicator != null)
                            SystemTray.ProgressIndicator.IsVisible = false;
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }
        #endregion

        #region NavigatedTo và BackKey for CancelPlay Youtube
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            YouTube.CancelPlay(); // used to reenable page
            if (SystemTray.ProgressIndicator!=null)
                SystemTray.ProgressIndicator.IsVisible = false;

            // your code here

            base.OnNavigatedTo(e);
        }


        protected override void OnBackKeyPress(CancelEventArgs e)
        {
		    if (YouTube.CancelPlay()) // used to abort current youtube download
			    e.Cancel = true;
		    else
		    {
			    // your code here
                
		    }
		    base.OnBackKeyPress(e);
        }
        #endregion

        #region Save XML Recent

//        public void SaveToXml(string fileName)
//        {
//            using (IsolatedStorageFile isolatedStorage = GetIsolatedStorageFile)
//            {
//                using (IsolatedStorageFileStream stream = isolatedStorage.OpenFile(fileName, FileMode.Create))
//                {
//                    XmlSerializer serializer = new XmlSerializer(typeof(List<TileItem>));

//                    using (XmlWriter xmlWriter = XmlWriter.Create(stream, new XmlWriterSettings() { Indent = true }))
//                    {
//                        serializer.Serialize(xmlWriter, Recent);
//                    }
//                }
//            }
//        }

//        /// <summary>
//        /// Gets the Isolated Storage File for the current platform.
//        /// </summary>
//        private IsolatedStorageFile GetIsolatedStorageFile
//        {
//            get
//            {
//#if (WINDOWS_PHONE)
//                return IsolatedStorageFile.GetUserStoreForApplication();
//#else
//        return IsolatedStorageFile.GetUserStoreForDomain();
//#endif
//            }
//        }
//        public void LoadFromXml(string fileName)
//        {
//            try
//            {
//                using (IsolatedStorageFile isolatedStorage = GetIsolatedStorageFile)
//                {
//                    // If the file exists, try and load it it's data.
//                    if (isolatedStorage.FileExists(fileName))
//                    {
//                        using (IsolatedStorageFileStream stream = isolatedStorage.OpenFile(fileName, FileMode.Open))
//                        {
//                            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<TileItem>));
//                            List<TileItem> data = (List<TileItem>)serializer.Deserialize(stream);
//                            Recent=data;
//                        }
//                    }
//                }
//            }
//            // Eat any exceptions unless debugging so that users don't see any errors.
//            catch
//            {

//            }

//            // We couldn't load the data, so just return a default instance of the class.
//            Recent= default(List<TileItem>);
//        }

//        /// <summary>
//        /// Gets if we are debugging the application or not.
//        /// </summary>
//        private bool IsDebugging
//        {
//            get
//            {
//#if (DEBUG)
//                // Extra layer of protection in case we accidentally release a version compiled in Debug mode.
//                if (System.Diagnostics.Debugger.IsAttached)
//                    return true;
//#endif
//                return false;
//            }
//        }
//        public static void FixErrorXmlFile(string fileName)
//        {
//            using (IsolatedStorageFile File = IsolatedStorageFile.GetUserStoreForApplication())
//            {
//                if (File.FileExists(fileName))
//                {
//                    File.DeleteFile(fileName);
//                }
//            }
//        }
#endregion
    }
}